//
//  fetchdata.swift
//  
//
//  Created by 赵康 on 2024/10/19.
//

func login(email: String, password: String) {
	let url = URL(string: "http://127.0.0.1:8080/auth/login")!
		// 根据 URL 来配置请求, 配置请求的顺序按照 HTTP 请求的模版来;
	var request = URLRequest(url: url)  // 基于 url 的请求;
	request.httpMethod = "POST"
	request.setValue("application/json", forHTTPHeaderField: "Content-Type")
	let loginData: [String: Any] = ["email": email, "password": password]
	request.httpBody = try? JSONSerialization.data(withJSONObject: loginData)
	
		// 请求配置完成, 现在准备发送; 发送是异步操作, 操作完成的逻辑由 compeltionHandler 处理
	let task = URLSession.shared.dataTask(with: request) {  // completionHandler
		data,
		response,
		error in
		guard let data = data, error == nil else {
			return
		}
			// 解析服务器返回的数据;
		if // 如果解析成功并且 sessionID 键的值可以转化为 string
			let jsonData = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
			let sessionID = jsonData["sessionID"] as? String {
			UserDefaults.standard.set(sessionID, forKey: "sessionID")
				// 记住这个 key 的名称, 后边从 UserDefault 中提取数据还要用到
		} else {
			print("处理服务器返回数据失败")
		}
	}
	task.resume()
}
